import 'dart:io';

import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:snippet_coder_utils/FormHelper.dart';

import '../models/data_model.dart';
import '../services/db_service.dart';

class AddEditProduct extends StatefulWidget {
  const AddEditProduct({super.key, this.model, this.isEditMode = false});

  final ProductModel? model;
  final bool isEditMode;

  @override
  State<AddEditProduct> createState() => _AddEditProductState();
}

class _AddEditProductState extends State<AddEditProduct> {
  GlobalKey<FormState> globalFormKey = GlobalKey<FormState>();
  late ProductModel model;
  List<dynamic> categories = [];
  DBService dbService = DBService();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    model = ProductModel(categoryId: -1, productName: "");

    if (widget.isEditMode) {
      model = widget.model!;
    }
    categories.add({"id": 1, "name": "T-shirts"});
    categories.add({"id": 2, "name": "shirts"});
    categories.add({"id": 3, "name": "Jeans"});
    categories.add({"id": 4, "name": "Tri"});
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.redAccent,
        automaticallyImplyLeading: true,
        title: Text(widget.isEditMode ? "Edit Mode" : "Add Mode"),
      ),
      body: Form(
        key: globalFormKey,
        child: _formUI(context),
      ),
      bottomNavigationBar: SizedBox(
        height: 110,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            FormHelper.submitButton("Save", () {
              if (validateAndSave()) {
                if (widget.isEditMode) {
                  dbService.updateProduct(model).then((value) {
                    FormHelper.showSimpleAlertDialog(
                      context,
                      "SQFLITE",
                      "success",
                      "ok",
                      () {
                        Navigator.pop(context);
                      },
                    );
                  });
                } else {
                  dbService.addProduct(model).then((value) {
                    FormHelper.showSimpleAlertDialog(
                      context,
                      "SQFLITE",
                      "added success",
                      "ok",
                      () {
                        Navigator.pop(context);
                      },
                    );
                  });
                }
              }
            },
                borderRadius: 10,
                btnColor: Colors.green,
                borderColor: Colors.green),
            FormHelper.submitButton("Cancel", () {},
                borderRadius: 10,
                btnColor: Colors.grey,
                borderColor: Colors.grey),
          ],
        ),
      ),
    );
  }

  Widget _formUI(context) {
    return SingleChildScrollView(
      child: Padding(
        padding: const EdgeInsets.all(10.0),
        child: Column(children: [
          FormHelper.inputFieldWidgetWithLabel(
            context,
            "productName",
            "product Name",
            "",
            (onValidate) {
              if (onValidate.isEmpty) {
                return "* required";
              }
              return null;
            },
            (onSaved) {
              model.productName = onSaved.toString().trim();
            },
            initialValue: model.productName!,
            showPrefixIcon: true,
            prefixIcon: const Icon(Icons.text_fields),
            borderRadius: 10,
            contentPadding: 15,
            fontSize: 14,
            labelFontSize: 14,
            paddingLeft: 0,
            paddingRight: 0,
            prefixIconPaddingLeft: 10,
          ),
          const SizedBox(
            height: 10,
          ),
          Row(
            children: [
              Flexible(
                flex: 1,
                child: FormHelper.inputFieldWidgetWithLabel(
                  context,
                  "productPrice",
                  "product Price",
                  "",
                  (onValidate) {
                    if (onValidate.isEmpty) {
                      return "* required";
                    }
                    return null;
                  },
                  (onSaved) {
                    model.price = double.parse(onSaved.trim());
                  },
                  initialValue:
                      model.price != null ? model.price.toString() : '',
                  showPrefixIcon: true,
                  prefixIcon: const Icon(Icons.text_fields),
                  borderRadius: 10,
                  contentPadding: 15,
                  fontSize: 14,
                  labelFontSize: 14,
                  paddingLeft: 0,
                  paddingRight: 0,
                  prefixIconPaddingLeft: 10,
                  isNumeric: true,
                ),
              ),
              Flexible(
                flex: 1,
                child: FormHelper.dropDownWidgetWithLabel(
                  context,
                  "product category",
                  "--select--",
                  model.categoryId,
                  categories,
                  (onChanged) {
                    model.categoryId = int.parse(onChanged);
                  },
                  (onValidate) {},
                  borderRadius: 10,
                  labelFontSize: 14,
                  paddingLeft: 0,
                  paddingRight: 0,
                  hintFontSize: 14,
                  prefixIcon: const Icon(Icons.category),
                  showPrefixIcon: true,
                  prefixIconPaddingLeft: 10,
                ),
              ),
            ],
          ),
          const SizedBox(
            height: 10,
          ),
          FormHelper.inputFieldWidgetWithLabel(
            context,
            "productDesc",
            "product Desc",
            "",
            (onValidate) {
              if (onValidate.isEmpty) {
                return "* required";
              }
              return null;
            },
            (onSaved) {
              model.productDesc = onSaved.toString().trim();
            },
            initialValue: model.productDesc ?? "",
            borderRadius: 10,
            contentPadding: 15,
            fontSize: 14,
            labelFontSize: 14,
            paddingLeft: 0,
            paddingRight: 0,
            prefixIconPaddingLeft: 10,
            isMultiline: true,
            multilineRows: 5,
          ),
          const SizedBox(
            height: 10,
          ),
          _picPicker(
              model.productPic ?? "",
              (file) => {
                    setState(() {
                      model.productPic = file.path;
                    })
                  }),
        ]),
      ),
    );
  }

  Widget _picPicker(
    String fileName,
    Function onFilePicked,
  ) {
    Future<XFile?> imageFile;
    ImagePicker picker = ImagePicker();

    return Column(
      children: [
        fileName != ""
            ? Image.file(
                File(fileName),
                width: 300,
                height: 300,
              )
            : SizedBox(
                child: Image.network(
                  "https://ducafecat.oss-cn-beijing.aliyuncs.com/ducafecat-video-flutter/avatar/00258VC3ly1gty0qy7h06j60hj0hjdhh02.jpg",
                  width: 350,
                  height: 250,
                  fit: BoxFit.scaleDown,
                ),
              ),
        Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            SizedBox(
              height: 35,
              width: 35,
              child: IconButton(
                padding: const EdgeInsets.all(0),
                icon: const Icon(
                  Icons.image,
                  size: 35,
                ),
                onPressed: () {
                  imageFile = picker.pickImage(source: ImageSource.gallery);
                  imageFile.then((file) async {
                    onFilePicked(file);
                  });
                },
              ),
            ),
            SizedBox(
              height: 35,
              width: 35,
              child: IconButton(
                padding: const EdgeInsets.all(0),
                icon: const Icon(
                  Icons.camera,
                  size: 35,
                ),
                onPressed: () {
                  imageFile = picker.pickImage(source: ImageSource.camera);
                  imageFile.then((file) async {
                    onFilePicked(file);
                  });
                },
              ),
            )
          ],
        )
      ],
    );
  }

  bool validateAndSave() {
    final form = globalFormKey.currentState;
    if (form!.validate()) {
      form.save();
      return true;
    }
    return false;
  }
}
